package com.tx.admin.util.common;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * 计数器工具
 * @author ldl
 *
 */

public class RedisUtil {

	private static RedisTemplate<Object, Object> redisTemplate ;
	
	public static RedisTemplate<Object, Object> getRedisTemplate() {
		return redisTemplate;
	}
	

	public static  void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
		RedisUtil.redisTemplate = redisTemplate;
	}


	/**
	 * 得到目前自增的值
	 * @param val
	 * @return
	 */
    public static long getIncrValue(Object val) {
       	byte[] key = val.toString().getBytes();
       	return redisTemplate.execute(new RedisCallback<Long>() {
         @Override
         public Long doInRedis(RedisConnection connection) throws DataAccessException {
        	
        	 byte[] bytes =  connection.get(key);
        	 if(bytes == null) {
        		 return (long)0;
        	 }
        	 return Long.parseLong(new String(bytes));
         }
     });
    }
    
    /**
     * 返回指定值的生存时间
     * @param val
     * @return
     */
    public static long ttl(Object val) {
    	byte[] key = val.toString().getBytes();
       	return redisTemplate.execute(new RedisCallback<Long>() {
         @Override
         public Long doInRedis(RedisConnection connection) throws DataAccessException {
        	 return connection.ttl(key);
         }
     });
    }

    /**
     * 将制定值自增并设置生存时间
     * @param val
     * @param seconds
     * @return
     */
    public static long incr(Object val,long seconds) {
    	byte[] key = val.toString().getBytes();
    	 return redisTemplate.execute(new RedisCallback<Long>() {
             @Override
             public Long doInRedis(RedisConnection connection) throws DataAccessException {
            	 long val = connection.incr(key);
            	 if(val == 1) {
            	  	 connection.expire(key, seconds);
            	 }
            	 return val;
             }
         });
    }
	
}
